from typing import Dict, List, Any

from langchain_core.messages import HumanMessage, AIMessage, BaseMessage

from config.logging_config import get_logger

logger = get_logger(__name__)


class MemoryUtils:
    """记忆管理相关的通用方法集合"""

    @staticmethod
    def get_memory_context(memory) -> str:
        """获取记忆上下文的通用方法"""
        if memory:
            try:
                memory_vars = memory.load_memory_variables({})
                return memory_vars.get('history', '')
            except Exception as e:
                logger.warning(f"获取记忆失败: {e}")
        return ""

    @staticmethod
    def convert_history_to_langchain_messages(history: List[Dict[str, Any]]) -> List[BaseMessage]:
        """
        将对话历史转换为LangChain消息格式
        
        Args:
            history: 对话历史列表
            
        Returns:
            LangChain消息列表
        """
        try:
            messages = []
            for msg in history:
                role = msg.get("role", "")
                content = msg.get("content", "")

                if role == "user" and content:
                    messages.append(HumanMessage(content=content))
                elif role == "assistant" and content:
                    messages.append(AIMessage(content=content))

            logger.debug(f"转换了 {len(messages)} 条消息为LangChain格式")
            return messages

        except Exception as e:
            logger.warning(f"转换消息格式失败: {e}")
            return []
